import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.List;
import java.util.Map;

/**
 * @author sk.z
 */
public class HttpURLConnectionExample {

    public static void main(String[] args) {
        System.out.println(httpGet("https://www.163.com"));
    }

    private static String httpGet(String urlStr) {
        StringBuilder content = new StringBuilder();
        BufferedReader reader = null;
        try {
            URL url = new URL(urlStr);
            HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
            urlConnection.setConnectTimeout(10000);
            urlConnection.setReadTimeout(5000);

            //获取返回头
            Map<String, List<String>> headerFields = urlConnection.getHeaderFields();
            headerFields.forEach((k,v)->{
                System.out.print(k);
                for (String s : v){
                    System.out.println("\t\t"+s);
                }
            });

            //判断返回码
            int responseCode = urlConnection.getResponseCode();
            if (responseCode != 200) {
                System.out.println("connect [" + urlStr + "] : " + responseCode + " " + urlConnection.getResponseMessage());
                return null;
            }

            //获取body
            reader = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
            String read;
            while ((read = reader.readLine()) != null) {
                content.append(read).append("\r\n");
            }
            return content.toString();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (reader != null) {
                try {
                    reader.close();
                } catch (IOException ignored) {
                }
            }
        }
        return null;
    }

}
